package io.lkt.modules.sys.wechat.handler;

import com.google.common.collect.Lists;
import com.tulele.vtool.model.PlatformSysInfo;
import io.lkt.common.utils.R;
import io.lkt.modules.sys.service.SysGzhService;
import io.lkt.modules.sys.utils.SysConstant;
import io.lkt.modules.sys.wechat.service.WeixinServiceDL;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.bean.menu.WxMenuRule;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/wechat")
public class WechatHandler {
    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private ObjectFactory<WeixinServiceDL> objectFactory;

    @PostMapping(value = "/createWxMenu", produces="application/json;charset=UTF-8")
    public R createWxMenu(@RequestHeader("gzhCode") String springProfilesActive, @RequestBody WxMenu wxMenu) {

        PlatformSysInfo platformSysInfoConfig = sysGzhService.getPlatformSysInfo(springProfilesActive);
        // 生成公众号菜单
        WxMenu menu = new WxMenu();

        if (wxMenu.getButtons() != null && wxMenu.getButtons().size() > 0) {
            List<WxMenuButton> list = Lists.newArrayList();
            int size = wxMenu.getButtons().size();
            for (int i = 0; i < size; i++) {
                // 主菜单
                WxMenuButton wxMenuButton = wxMenu.getButtons().get(i);
                if (wxMenuButton != null && StringUtils.isNotBlank(wxMenuButton.getName())) {
                    // 重新构造一个主菜单
                    WxMenuButton firstLevel = new WxMenuButton();
                    firstLevel.setName(wxMenuButton.getName());
                    String type = wxMenuButton.getType();
                    if (StringUtils.isNotEmpty(type)) {
                        firstLevel.setType(type);
                        if (type.equals(WxConsts.MenuButtonType.VIEW)) {
                            firstLevel.setUrl(getMenuUrl(platformSysInfoConfig, wxMenuButton.getUrl(), springProfilesActive));
                        } else if (type.equals(WxConsts.MenuButtonType.CLICK)) {
                            firstLevel.setKey(getMenuKey(platformSysInfoConfig, wxMenuButton.getKey()));
                        }
                    }

                    if (wxMenuButton.getSubButtons() != null && wxMenuButton.getSubButtons().size() > 0) {
                        List<WxMenuButton> subList = Lists.newArrayList();
                        int subSize = wxMenuButton.getSubButtons().size();
                        for (int j = 0; j < subSize; j++) {
                            // 子菜单
                            WxMenuButton subWxMenuButton = wxMenuButton.getSubButtons().get(j);
                            if (subWxMenuButton != null && StringUtils.isNotBlank(subWxMenuButton.getName())) {
                                // 重新构造一个子菜单
                                WxMenuButton secondLevel = new WxMenuButton();
                                secondLevel.setName(subWxMenuButton.getName());
                                secondLevel.setType(subWxMenuButton.getType());

                                if (subWxMenuButton.getType().equals(WxConsts.MenuButtonType.VIEW)) {
                                    secondLevel.setUrl(getMenuUrl(platformSysInfoConfig, subWxMenuButton.getUrl(), springProfilesActive));
                                } else if (subWxMenuButton.getType().equals(WxConsts.MenuButtonType.CLICK)) {
                                    secondLevel.setKey(getMenuKey(platformSysInfoConfig, subWxMenuButton.getKey()));
                                }
                                subList.add(secondLevel);
                            }
                        }
                        firstLevel.setSubButtons(subList);
                    }
                    list.add(firstLevel);
                }
            }
            menu.setButtons(list);
        }
        WxMenuRule matchRule = wxMenu.getMatchRule();
        String clientPlatformType = matchRule.getClientPlatformType();
        if (clientPlatformType.equals("1")) { // 针对 IOS
            menu.setMatchRule(matchRule);
        } else {
            menu.setMatchRule(null);
        }

        try {
            WeixinServiceDL weixinService= objectFactory.getObject();
            weixinService.reSetConfigStorage(springProfilesActive);
            weixinService.getMenuService().menuDelete();
            weixinService.getMenuService().menuCreate(menu);
        } catch (WxErrorException e) {
            e.printStackTrace();
            return R.error("失败");
        }
        return R.ok("成功");
    }

    private String getMenuUrl(PlatformSysInfo platformSysInfoConfig, String urlCode, String springProfilesActive) {
        String url = "";
        switch (urlCode) {
            case "0":
                if (springProfilesActive.equalsIgnoreCase("prodzx1") ||  //专业号(文章/视频)
                        springProfilesActive.equalsIgnoreCase("prodhyxt") ||
                        springProfilesActive.equalsIgnoreCase("prodtjs") ||
                        springProfilesActive.equalsIgnoreCase("prodxscja")||
                        springProfilesActive.equalsIgnoreCase("prodbdxzs")||
                        springProfilesActive.equalsIgnoreCase("back_zkt")||
                        springProfilesActive.equalsIgnoreCase("prodshjj")||
                        springProfilesActive.equalsIgnoreCase("prodbkwz")||
                        springProfilesActive.equalsIgnoreCase("prodgjhkpt")

                ){
                    url = platformSysInfoConfig.getArticleListMenuUrl().replace("list.html","listTxp.html");
                }else {//非专业号(文章/视频)
                    url = platformSysInfoConfig.getArticleListMenuUrl();
                }
                break;
            case "1":
                url = platformSysInfoConfig.getClockMenuUrl(); // 早晚安打卡
                break;
            case "2":
                url = platformSysInfoConfig.getFrontDomain()+"pages/officialAccounts/poster.html"; // 获客海报
                break;
            case "3":
                url = platformSysInfoConfig.getConnectionPlazaUrl(); // 人脉广场
                break;
            case "4":
                url = platformSysInfoConfig.getArticleListMenuUrl()+"?return=2"; // 团队管理
                break;
            case "5":
                url = platformSysInfoConfig.getCustomerMenuUrl(); // 客户
                break;
            case "6":
                url = platformSysInfoConfig.getOpenMemberMenuUrl()+"?mt=0"; // 会员权益
                break;
            case "7":
                url = platformSysInfoConfig.getSetUpMenuUrl(); // 个人中心
                break;
            case "8":
                url = platformSysInfoConfig.getFrontDomain()+"pages/commercialCollege/index.html"; // 开单学院
                break;
            case "9":
                url = platformSysInfoConfig.getMicroStationMenuUrl(); // 我的微站
                break;
        }
        return url;
    }

    private String getMenuKey(PlatformSysInfo platformSysInfoConfig, String keyCode) {
        String key = "";
        switch (keyCode) {
            case "0":
                key = platformSysInfoConfig.getCooperationUseMenuEventKey(); // 邀请有奖
                break;
            case "1":
                key = SysConstant.V1003_CLASS_KEFU2; // 联系客服
                break;
            case "2":
                key = SysConstant.V1004_CLASS_PUNCH_CLOCK; // 早晚安
                break;
            case "3":
                key = SysConstant.ADD_ARTICLE_VIDEO; // 添加文章或视频
                break;
        }
        return key;
    }
}
